package org.jeecg.modules.handler;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.cmbCloudDirectLink.utils.CMBApi;
import org.jeecg.common.api.dto.BankSetDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manage.entity.CaishuiBusinessBank;
import org.jeecg.modules.manage.entity.CaishuiTransactionFlow;
import org.jeecg.modules.manage.mapper.MCaishuiBusinessBankMapper;
import org.jeecg.modules.manage.mapper.MCaishuiRechargeMapper;
import org.jeecg.modules.manage.service.IMCaishuiBusinessBankService;
import org.jeecg.modules.manage.service.IMCaishuiCompanySetService;
import org.jeecg.modules.manage.service.IMCaishuiTransactionFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Description: 获取昨天服务公司所有记账子单元交易流水
 *  定时任务
 * @Author: yfkj
 * @Date:   2023-01-05
 * @Version: V1.0
 */
@Component
@Slf4j
public class TransactionFlowJobHandler {

    @Autowired
    private IMCaishuiCompanySetService imCaishuiCompanySetService;
    @Resource
    private IMCaishuiBusinessBankService imCaishuiBusinessBankService;
    @Autowired
    private IMCaishuiTransactionFlowService imCaishuiTransactionFlowService;

    /**
     * 获取交易流水
     * @param params 服务公司账号
     * @return
     */
    @XxlJob(value = "getTransactionFlowJob")
    public ReturnT<String> getTransactionFlowJobHandler(String params) {
        //获取昨天日期，格式：20230403
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DATE, -1);
        String yesterday = DateUtils.sdf8.format(cal.getTime());

        //根据账号查询服务公司设置相关信息
        BankSetDTO bankSetDTO = imCaishuiCompanySetService.queryCompanySet(params);
        if (oConvertUtils.isEmpty(bankSetDTO)) {
            log.error("服务公司【"+params+"】暂未设置秘钥相关配置！");
            return ReturnT.FAIL;
        }
        //查询账户下所有记账子单元昨日交易
        Result<?> result = CMBApi.querySubUnitHistoryTransaction(params, "",yesterday,yesterday,"", bankSetDTO);
        if(!result.isSuccess()){
            log.error("服务公司【"+params+"】调用接口[查询账户下所有记账子单元昨日交易]失败：" + result.getMessage());
            return ReturnT.FAIL;
        } else if (oConvertUtils.isEmpty(result.getResult())){
            log.error("服务公司【"+params+"】在"+yesterday+"日暂未交易！ ");
            return ReturnT.SUCCESS;
        }

        //处理交易记录
        JsonArray jsonArray = new GsonBuilder().create().fromJson(result.getResult().toString(), JsonArray.class);
        for (JsonElement jsonElement : jsonArray) {
            try {
                String accnbr = jsonElement.getAsJsonObject().get("accnbr").getAsString();//帐号
                String dmanbr = jsonElement.getAsJsonObject().get("dmanbr").getAsString();//记账子单元编号
                String trxnbr = jsonElement.getAsJsonObject().get("trxnbr").getAsString();//记账流水号
                //判断交易流水是否已入库
                long count = imCaishuiTransactionFlowService.count(new LambdaQueryWrapper<CaishuiTransactionFlow>()
                        .eq(CaishuiTransactionFlow::getAccnbr,accnbr).eq(CaishuiTransactionFlow::getDmanbr,dmanbr)
                        .eq(CaishuiTransactionFlow::getTrxnbr,trxnbr));
                if (count > 0) continue;

                //根据账号和记账子单元编号查询商户银行信息
                CaishuiBusinessBank businessBank = imCaishuiBusinessBankService.getOne(new LambdaQueryWrapper<CaishuiBusinessBank>()
                        .select(CaishuiBusinessBank::getTenantId,CaishuiBusinessBank::getBusinessId,
                                CaishuiBusinessBank::getServiceCompanyId, CaishuiBusinessBank::getName)
                        .eq(CaishuiBusinessBank::getMainAccount,accnbr).eq(CaishuiBusinessBank::getSubAccountId,dmanbr));
                if(oConvertUtils.isEmpty(businessBank)) continue;
                String dmanam = oConvertUtils.isEmpty(jsonElement.getAsJsonObject().get("dmanam")) ? "" : jsonElement.getAsJsonObject().get("dmanam").getAsString();
                String ccynbr = jsonElement.getAsJsonObject().get("ccynbr").getAsString();
                double trxamt = jsonElement.getAsJsonObject().get("trxamt").getAsDouble();
                String trxdir = jsonElement.getAsJsonObject().get("trxdir").getAsString();
                String trxdat = jsonElement.getAsJsonObject().get("trxdat").getAsString();
                String trxtim = jsonElement.getAsJsonObject().get("trxtim").getAsString();
                String rpyacc = oConvertUtils.isEmpty(jsonElement.getAsJsonObject().get("rpyacc")) ? "" : jsonElement.getAsJsonObject().get("rpyacc").getAsString();
                String rpynam = oConvertUtils.isEmpty(jsonElement.getAsJsonObject().get("rpynam")) ? "" : jsonElement.getAsJsonObject().get("rpynam").getAsString();
                String trxtxt = oConvertUtils.isEmpty(jsonElement.getAsJsonObject().get("trxtxt")) ? "" : jsonElement.getAsJsonObject().get("trxtxt").getAsString();
                String narinn = oConvertUtils.isEmpty(jsonElement.getAsJsonObject().get("narinn")) ? "" : jsonElement.getAsJsonObject().get("narinn").getAsString();
                String mthflg = oConvertUtils.isEmpty(jsonElement.getAsJsonObject().get("mthflg")) ? "" : jsonElement.getAsJsonObject().get("mthflg").getAsString();
                String balflg = oConvertUtils.isEmpty(jsonElement.getAsJsonObject().get("balflg")) ? "" : jsonElement.getAsJsonObject().get("balflg").getAsString();
                String onlbal = oConvertUtils.isEmpty(jsonElement.getAsJsonObject().get("onlbal")) ? "" : jsonElement.getAsJsonObject().get("onlbal").getAsString();
                String rvstag = oConvertUtils.isEmpty(jsonElement.getAsJsonObject().get("rvstag")) ? "" : jsonElement.getAsJsonObject().get("rvstag").getAsString();
                String autflg = oConvertUtils.isEmpty(jsonElement.getAsJsonObject().get("autflg")) ? "" : jsonElement.getAsJsonObject().get("autflg").getAsString();

                //添加记账子单元交易流水
                CaishuiTransactionFlow transactionFlow = new CaishuiTransactionFlow();
                transactionFlow.setCompanyId(businessBank.getServiceCompanyId());
                transactionFlow.setBusinessId(businessBank.getBusinessId());
                transactionFlow.setTenantId(businessBank.getTenantId());
                transactionFlow.setCompanyName(businessBank.getName());
                transactionFlow.setAccnbr(accnbr);
                transactionFlow.setDmanbr(dmanbr);
                transactionFlow.setDmanam(dmanam);
                transactionFlow.setTrxnbr(trxnbr);
                transactionFlow.setCcynbr(ccynbr);
                transactionFlow.setTrxamt(trxamt);
                transactionFlow.setTrxdir(trxdir);
                transactionFlow.setTrxtim(trxdat + trxtim);//交易日期 + 交易时间
                transactionFlow.setRpyacc(rpyacc);
                transactionFlow.setRpynam(rpynam);
                transactionFlow.setTrxtxt(trxtxt);
                transactionFlow.setNarinn(narinn);
                transactionFlow.setMthflg(mthflg);
                transactionFlow.setBalflg(balflg);
                transactionFlow.setOnlbal(onlbal);
                transactionFlow.setRvstag(rvstag);
                transactionFlow.setAutflg(autflg);
                imCaishuiTransactionFlowService.save(transactionFlow);
            } catch (Exception e){
                log.error("处理交易记录["+jsonElement.getAsJsonObject()+"]失败：" + e.getMessage());
                continue;
            }
        }
        return ReturnT.SUCCESS;
    }

}
